package com.pgeneral.user.management.service.impl;

import cn.hutool.core.date.DateTime;
import com.pgeneral.user.management.dao.DepartmentInfoMapper;
import com.pgeneral.user.management.dao.MbGeneralSignatureMapper;
import com.pgeneral.user.management.dao.SopScopeDataMapper;
import com.pgeneral.user.management.dto.GlobalInfosDTO;
import com.pgeneral.user.management.entity.DepartmentInfo;
import com.pgeneral.user.management.entity.MbGeneralSignature;
import com.pgeneral.user.management.entity.UserInfo;
import com.pgeneral.user.management.exception.MyException;
import com.pgeneral.user.management.util.DateUtils;
import com.pgeneral.user.management.util.FileStoreUtils;
import com.pgeneral.user.management.util.UUIDGenerator;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.pgeneral.user.management.dao.UserInfoMapper;
import com.pgeneral.user.management.service.UserInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.pgeneral.user.management.constant.URLConstantUtils.*;

/**
 * @author 龙
 * @create 2020/6/30 11:41
 */
@Slf4j
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Resource
    private UserInfoMapper userinfoMapper;

    @Resource
    private MbGeneralSignatureMapper mbGeneralSignatureMapper;

    @Resource
    private DepartmentInfoMapper departmentInfoMapper;

    @Resource
    private SopScopeDataMapper sopScopeDataMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(List<UserInfo> userInfos) {

        if (userInfos != null && userInfos.size() > 0) {
            if (knowledgeIsRepeat(userInfos)) {
                throw new MyException("1001", "登录名重复，请重新修改!");
            }
            Date data = new Date();
            //文件路径
            String path = SIGN_FILE_PATH + new SimpleDateFormat("yyyy/MM/dd").format(data);
            userInfos.stream().forEach(item -> {
                if (item.getUserName() != null && !"".equals(item.getUserName())) {
                    int i = userinfoMapper.getRepatData(item.getUserName(), null);
                    if (i > 0) {
                        throw new MyException("1001", "登录名重复，请重新修改!");
                    }
                    item.setUserId(UUIDGenerator.getUUID());
                }
                log.info("文件路径为：{}", path);
                if (item.getMessage() != null && !("").equals(item.getMessage())) {
                    boolean b = FileStoreUtils.createFile(path);
                    if (b) {
                        String filePath = path +  item.getUserId() + ".txt";
                        item.setPath(filePath);
                        FileStoreUtils.saveFileMessage(filePath, item.getMessage());
                    }
                    //feat:20240923
                    List<MbGeneralSignature> mgsList = userInfos.stream().map(e -> {
                        MbGeneralSignature mbGeneralSignature = new MbGeneralSignature();
                        mbGeneralSignature.setUserId(e.getUserId());
                        //存入数据库中格式处理
                        String finalPath = "\\" + e.getPath().replace(SIGN_FILE_PATH,"")
                                .replace("/","\\");
                        mbGeneralSignature.setSignature(finalPath);
                        // 没有时间就获取当前本地时间
                        mbGeneralSignature.setCreateTime(StringUtils.isBlank(e.getCreateTime()) ? DateUtils.getCurrentDateString() : e.getCreateTime());
                        return mbGeneralSignature;
                    }).collect(Collectors.toList());
                    //删掉所有为null的元素
                    mgsList.removeAll(Collections.singleton(null));
                    final Integer count = mbGeneralSignatureMapper.batchinsert(mgsList);
                    log.debug("batch insert count:{}",count);
                }
            });
            return userinfoMapper.insert(userInfos);
        }
        throw new MyException("1001", "请输入用户参数!");

    }

    /**
     * 判断List<UserInfo>的对象code是否有重复，有重复true
     *
     * @param orderList
     * @return
     */
    private Boolean knowledgeIsRepeat(List<UserInfo> orderList) {
        Set<UserInfo> set = new TreeSet<UserInfo>(new Comparator<UserInfo>() {
            @Override
            public int compare(UserInfo a, UserInfo b) {
                System.out.println("2");
                // 字符串则按照asicc码升序排列
                return a.getUserName().compareTo(b.getUserName());
            }
        });
        set.addAll(orderList);
        if (set.size() < orderList.size()) {
            return true;
        }
        return false;
    }

    @Override
    public List<UserInfo> getUserInfoTable(UserInfo userInfo) {
        return userinfoMapper.getUserInfoTable(userInfo);
    }

    /**
     * 查询所有用户
     *
     * @return
     */
    @Override
    public List<UserInfo> getAllUserInfos() {
        return userinfoMapper.getAllUserInfos();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUserInfoTable(UserInfo userInfo) {
        if (userInfo.getUserName() != null && !"".equals(userInfo.getUserName())) {
            int i = userinfoMapper.getRepatData(userInfo.getUserName(), userInfo.getUserId());
            if (i > 0) {
                throw new MyException("1001", "登录名重复，请重新修改!");
            }
        }
        Date data = new Date();
        //文件路径
        String path = SIGN_FILE_PATH + new SimpleDateFormat("yyyy/MM/dd").format(data);
        log.info("文件路径为：{}", path);
        //如果参数签名信息不为空
        if (userInfo.getMessage() != null && !("").equals(userInfo.getMessage())) {
            boolean b = FileStoreUtils.createFile(path);
            if (b) {
                String filePath = path + userInfo.getUserId() + ".txt";
                userInfo.setPath(filePath);
                FileStoreUtils.saveFileMessage(filePath, userInfo.getMessage());
            }
            //20240923
            MbGeneralSignature mbGeneralSignature = new MbGeneralSignature();
            mbGeneralSignature.setUserId(userInfo.getUserId());
            //存入数据库中格式处理
            String finalPath = "\\" + userInfo.getPath().replace(SIGN_FILE_PATH,"")
                    .replace("/","\\");
            mbGeneralSignature.setSignature(finalPath);
            mbGeneralSignature.setCreateTime(userInfo.getCreateTime());
            final Integer count = mbGeneralSignatureMapper.insert(mbGeneralSignature);
            log.debug("batch insert count:{}",count);
        }
        return userinfoMapper.updateUserInfoBySign(userInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateIsDeletefromUserInfoTable(List<String> ids) {
        return userinfoMapper.updateIsDeletefromUserInfoTable(ids);
    }

    @Override
    public List<GlobalInfosDTO> getGlobalInfos(UserInfo userInfo) {
        List<GlobalInfosDTO> globalInfos = this.userinfoMapper.getGlobalInfos(userInfo);
        if (globalInfos.size() != 0) {
            for (GlobalInfosDTO globalInfosDTO1 : globalInfos) {
                if (globalInfosDTO1.getRoleName() == null || "".equals(globalInfosDTO1.getRoleName())) {
                    String[] split = globalInfosDTO1.getRoleId().split("\\|");
                    List<String> stringList = Arrays.asList(split);
                    List<GlobalInfosDTO> globalInfosDTOByRoleId = getGlobalInfosDTOByRoleId(stringList);
                    List<String> scopeNameList = (List<String>) globalInfosDTOByRoleId.stream().map(GlobalInfosDTO::getScopeName).collect(Collectors.toList());
                    String scopeName = String.join("|", (Iterable) scopeNameList);
                    globalInfosDTO1.setScopeName(scopeName);
                    List<String> roleNameList = (List<String>) globalInfosDTOByRoleId.stream().map(GlobalInfosDTO::getRoleName).collect(Collectors.toList());
                    String roleName = String.join("|", (Iterable) roleNameList);
                    globalInfosDTO1.setRoleName(roleName);
                }
            }
            GlobalInfosDTO globalInfosDTO = globalInfos.get(0);
            if (globalInfosDTO.getDepartmentName() == null) {
                List<GlobalInfosDTO> objectList = (List<GlobalInfosDTO>) globalInfos.stream().map(globalInfosDTO1 -> {
                    globalInfosDTO1.setDepartmentName(globalInfosDTO1.getDepartmentId());
                    globalInfosDTO1.setScopeName(globalInfosDTO1.getRoleId());
                    return globalInfosDTO1;
                }).collect(Collectors.toList());
                return objectList;
            }
            return globalInfos;
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updatePasswordByUserId(UserInfo userInfo) {
        return userinfoMapper.updatePasswordByUserId(userInfo);

    }

    @Override
    public List<GlobalInfosDTO> getThreeTable(UserInfo userInfo) {
        return userinfoMapper.getThreeTable(userInfo);
    }

    @Override
    public List<GlobalInfosDTO> getLoginUser(UserInfo userInfo) {
        if (userInfo.getUserName() == null || "".equals(userInfo.getUserName()) || userInfo.getPasswordWord() == null || "".equals(userInfo.getPasswordWord())) {
            throw new MyException("1002", "用户名或密码不能为空！");
        }
        List<GlobalInfosDTO> loginUser = this.userinfoMapper.getLoginUserForPaid(userInfo);
        if (loginUser.size() != 0) {
            for (GlobalInfosDTO globalInfosDTO1 : loginUser) {
                //如果没有获取到角色名称
                if (globalInfosDTO1.getRoleName() == null || "".equals(globalInfosDTO1.getRoleName())) {
                    String[] split = globalInfosDTO1.getRoleId().split("\\|");
                    List<String> stringList = Arrays.asList(split);
                    //获取(角色名称，前端菜单栏显示模块id，前端菜单栏显示模块名称)
                    List<GlobalInfosDTO> globalInfosDTOByRoleId = getGlobalInfosDTOByRoleId(stringList);
                    //ScopeName=(更改日志,信息汇总,检测任务,标准作业,变更记录,方法更新)等,有重复也无所谓,有就能显示
                    List<String> scopeNameList = (List<String>) globalInfosDTOByRoleId.stream().map(GlobalInfosDTO::getScopeName).collect(Collectors.toList());
                    String scopeName = String.join("|", (Iterable) scopeNameList);
                    globalInfosDTO1.setScopeName(scopeName);
                    //一样的逻辑，获取角色名称（管理员|审核人|校核人|计数人等）
                    List<String> roleNameList = (List<String>) globalInfosDTOByRoleId.stream().map(GlobalInfosDTO::getRoleName).collect(Collectors.toList());
                    String roleName = String.join("|", (Iterable) roleNameList);
                    globalInfosDTO1.setRoleName(roleName);
                }
            }
            //获取第一个被查询到的值
            GlobalInfosDTO globalInfosDTO = loginUser.get(0);
            if (globalInfosDTO.getDepartmentName() == null) {
                List<GlobalInfosDTO> objectList = (List<GlobalInfosDTO>) loginUser.stream().map(globalInfosDTO1 -> {
                    DepartmentInfo departmentinfo = new DepartmentInfo();
                    departmentinfo.setDepartmentId(globalInfosDTO1.getDepartmentId());
                    List<DepartmentInfo> departmentinfoTable = departmentInfoMapper.getDepartmentinfoTable(departmentinfo);
                    if (CollectionUtils.isEmpty(departmentinfoTable)){
                        globalInfosDTO1.setDepartmentName(departmentinfoTable.get(0).getDepartmentName());
                    }else{
                        globalInfosDTO1.setDepartmentName(globalInfosDTO1.getDepartmentId());
                    }
                    globalInfosDTO1.setScopeName(globalInfosDTO1.getRoleId());
                    return globalInfosDTO1;
                }).collect(Collectors.toList());
                return objectList;
            }
            return loginUser;
        }
        return new ArrayList<>();
    }

    /**
     * 根据roleId查询
     */
    private List<GlobalInfosDTO> getGlobalInfosDTOByRoleId(List<String> roleIds) {
        return userinfoMapper.getGlobalInfosDTOByRoleId(roleIds);
    }

    @Override
    public List<UserInfo> getSign(List<String> userId) {
        List<UserInfo> info = new ArrayList<>();
        List<Map<String, String>> sign = userinfoMapper.getSign(userId);
        sign.forEach(s -> {
            UserInfo userInfo = new UserInfo();
            if (s.get("path") != null) {
                String messages = FileStoreUtils.getFileMessages(s.get("path"));
                userInfo.setMessage(messages);
            }
            userInfo.setUserName(s.get("UserName"));
            info.add(userInfo);
        });
        return info;
    }
}

